﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Collections;

namespace Aim2 {
    class Level : IObjectContainer {
        public Player Player { get; set; }
        List<Asteroid> asteroidField;

        Stack<AnimatedObject> ToRemove;

        public Level() {
            Player = new Player(this);
            asteroidField = new List<Asteroid>();
            ToRemove = new Stack<AnimatedObject>();
            CollisionManager.Instance.Register(this);
        }

        public void HandleInput(InputState input) {
            if (Player != null)
                Player.HandleInput(input);
            if (input.CurrentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl))
                asteroidField.Add(new Asteroid(new Vector2(Game.Random.Next(0, 400), 0), this));
        }

        public void Load(ContentManager content, Viewport viewport) {
            Player.Load(content, viewport);
            new Asteroid(Vector2.Zero, null).Load(content, viewport);
        }

        public void Update(float elapsed) {
            if(Player != null)
                Player.Update(elapsed);

            foreach(Asteroid a in asteroidField)
                a.Update(elapsed);
        }

        public void Draw(SpriteBatch spriteBatch) {
            if (Player != null)
                Player.Draw(spriteBatch);
            foreach (Asteroid a in asteroidField)
                a.Draw(spriteBatch);
        }

        public void AddToRemovalList(AnimatedObject a) {
            ToRemove.Push(a);
        }

        public void RemovePending() {
            AnimatedObject a;
            while (ToRemove.Count > 0) {
                a = ToRemove.Pop();
                if (a is Asteroid)
                    asteroidField.Remove((Asteroid)a);
                if (a is Player)
                    Player = null;
            }
        }

        public IEnumerator<AnimatedObject> GetEnumerator() {
            foreach (Asteroid a in asteroidField)
                yield return a;
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }
}
